package me.zhengjie.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.ExceptionDepthComparator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Collections;

/**
 * Created by bruce on 20/3/21.
 */
public class HttpResponseUtils {
    public static ResponseEntity passDefaultResponse(String message,HttpStatus status) {
        JSONObject obj = new JSONObject();
        obj.put("status", status.value());
        obj.put("message",message);
        return new ResponseEntity(obj,status);
    }

    public static ResponseEntity passDefaultResponse(Exception ex) {
        JSONObject obj = new JSONObject();
        obj.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
        if( ex instanceof  org.springframework.dao.DataIntegrityViolationException) {
            obj.put("message","该数据被其他记录引用,不能删除");
        } else if(ex instanceof  org.springframework.dao.EmptyResultDataAccessException) {
            obj.put("message", "记录不存在");
        } else {
            obj.put("message", ex.getMessage());
        }
        return new ResponseEntity(obj, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    /*
    public static ResponseEntity passDefaultErrorResponse(String message, HttpStatus status) {
        LinkedMultiValueMap map = new LinkedMultiValueMap(0);
        map.put("statusText", Collections.singletonList(message));
        return new ResponseEntity(null,map,status);
    }*/
}
